from django.shortcuts import render
from django.template.loader import render_to_string
from bootcamp.activities.models import Notification
from django.http import HttpResponse, HttpResponseBadRequest
from django.contrib.auth.decorators import login_required
from bootcamp.decorators import ajax_required

@login_required
def notifications(request):
    user = request.user
    notifications = Notification.objects.filter(to_user=user)
    unread = Notification.objects.filter(to_user=user, is_read=False)
    for notification in unread:
        notification.is_read = True
        notification.save()        
    return render(request, 'activities/notifications.html', {'notifications': notifications})

@login_required
@ajax_required
def last_notifications(request):
    user = request.user
    notifications = Notification.objects.filter(to_user=user, is_read=False)[:5]
    for notification in notifications:
        notification.is_read = True
        notification.save()
    return render(request, 'activities/last_notifications.html', {'notifications': notifications})

def check_notifications(request):
    user = request.user
    notifications = Notification.objects.filter(to_user=user, is_read=False)[:5]
    return HttpResponse(len(notifications))

def appnote(request):
    user = request.user
#    unread = Notification.objects.filter(to_user=user, is_read=False)
    unread = Notification.objects.filter(to_user=user, is_read=False)
    html = u''
    for note in unread:
        html = u'{0}{1}'.format(html, render_to_string('activities/appnote.html', {
            'notification': note,
            })
        )
    return HttpResponse(html)

def del_note(request):
    user = request.user
    note_id = request.POST.get("note_id")
    notification = Notification.objects.get(pk=note_id)
    notification.is_read = True
    notification.save()        
    return HttpResponse(True)
